package com.bnlr.lrparking.appui.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.appui.web.WebActivity;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.constant.ConstantFlag;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.event.CloseLoginEvent;
import com.bnlr.lrparking.model.UserByApp;
import com.bnlr.lrparking.model.VerifyCodeM;
import com.bnlr.lrparking.util.CommonUtil;
import com.bnlr.lrparking.util.CountDownTimerUtils;
import com.bnlr.lrparking.view.ClearEditText;
import com.bnlr.lrparking.wxapi.WXEntryActivity;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;

/**
 * 验证码登录
 *
 * @author hp
 * @date 2017/7/25
 */
public class VerificaActivity extends BaseActivity {

    @BindView(R.id.iv_wx_login)
    ImageView ivWxLogin;

    private RelativeLayout relyVerifica;
    private TextView Verifica, tVerificaPawLogin, tvLoginBtn, tv_clause;
    private ClearEditText edVerificaPhon, edLoginVerifica;
    private String phone;
    private String yzm = "";
    private String pwd = "";
    private String appConfigPhone;
    private RelativeLayout rely_forget_pwd;
    private ImageView image;
    /**
     * 登录方式 1 验证码  2 密码
     */
    private int isLoginType = 1;
    private RelativeLayout rely_register;
    private ImageView ivBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verifica_code);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initView();
    }

    private void initView() {
        AppConfig.getInstance().putString("userName", "");
        rely_register = (RelativeLayout) findViewById(R.id.rely_register);
        rely_register.setOnClickListener(this);
        appConfigPhone = AppConfig.getInstance().getString("userName", "");
        relyVerifica = (RelativeLayout) findViewById(R.id.rely_verifica);
        Verifica = (TextView) findViewById(R.id.tv_verifica);
        edVerificaPhon = (ClearEditText) findViewById(R.id.ed_verifica_phone);
        edVerificaPhon.setText(appConfigPhone);
        rely_forget_pwd = (RelativeLayout) findViewById(R.id.rely_forget_pwd);
        //将光标移至文字末尾
        edVerificaPhon.setSelection(appConfigPhone.length());
        tVerificaPawLogin = (TextView) findViewById(R.id.tv_verifica_paw_login);
        image = (ImageView) findViewById(R.id.imageView17);
        edLoginVerifica = (ClearEditText) findViewById(R.id.ed_login_verifica);
        tvLoginBtn = (TextView) findViewById(R.id.tv_login_btn);
        tv_clause = (TextView) findViewById(R.id.tv_clause);
        ivBack = (ImageView) findViewById(R.id.iv_nav_back);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        edVerificaPhon.addTextChangedListener(mTextWatcher);
        edLoginVerifica.addTextChangedListener(mTextWatcher1);
        tVerificaPawLogin.setOnClickListener(this);
        rely_forget_pwd.setOnClickListener(this);
        tv_clause.setOnClickListener(this);
        Verifica.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SendYzm();
            }
        });
        tvLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isLoginType == ConstantFlag.INTEGER_FLAG_ONE) {
                    // 手机验证码登录
                    loginByType(0);
                } else if (isLoginType == ConstantFlag.INTEGER_FLAG_TWO) {
                    // 账号密码登录
                    loginByType(1);
                }
            }
        });

        ivWxLogin.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 判断手机号
     */
    private TextWatcher mTextWatcher = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            phone = edVerificaPhon.getText().toString();
            //判断获取验证码按钮
            if (RegexUtils.isMobileExact(phone)) {
                Verifica.setEnabled(true);
                if (!edLoginVerifica.getText().toString().equals("")) {
                    tvLoginBtn.setEnabled(true);
                }
            } else {
                Verifica.setEnabled(false);
                tvLoginBtn.setEnabled(false);
            }
        }
    };

    /**
     * 判断验证码的监听
     */
    private TextWatcher mTextWatcher1 = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            pwd = edLoginVerifica.getText().toString();
            yzm = edLoginVerifica.getText().toString();
            phone = edVerificaPhon.getText().toString();
            // 判断开车按钮
            if (RegexUtils.isMobileExact(phone) && !edLoginVerifica.getText().toString().equals("")) {
                tvLoginBtn.setEnabled(true);
            } else {
                tvLoginBtn.setEnabled(false);
            }
        }
    };

    /**
     * 60秒的倒计时
     *
     * @param verifica 显示倒计时的控件
     */
    private void setVerifica(TextView verifica) {
        CountDownTimerUtils mCountDownTimerUtils = new CountDownTimerUtils(verifica, 60000, 1000);
        mCountDownTimerUtils.start();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_verifica_paw_login:
                edLoginVerifica.setText("");
                if (isLoginType == 1) {
                    isLoginType = 2;
                    tVerificaPawLogin.setText("验证码登录");
                    image.setImageResource(R.mipmap.password);
                    rely_forget_pwd.setVisibility(View.VISIBLE);
                    relyVerifica.setVisibility(View.GONE);
                    edLoginVerifica.setHint("请输入密码");
                    edLoginVerifica.setFilters(new InputFilter[]{new InputFilter.LengthFilter(16)});
                    edLoginVerifica.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    edLoginVerifica.setTransformationMethod(PasswordTransformationMethod.getInstance());
                } else if (isLoginType == 2) {
                    isLoginType = 1;
                    tVerificaPawLogin.setText("账号密码登录");
                    image.setImageResource(R.mipmap.verification);
                    rely_forget_pwd.setVisibility(View.GONE);
                    relyVerifica.setVisibility(View.VISIBLE);
                    edLoginVerifica.setHint("请输入验证码");
                    edLoginVerifica.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
                    edLoginVerifica.setInputType(InputType.TYPE_CLASS_NUMBER);
                    edLoginVerifica.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }
                break;
            case R.id.rely_forget_pwd:
                startActivity(ForgetPassWordActivity.class);
                break;
            case R.id.rely_register:
                Intent intentRegister = new Intent(VerificaActivity.this, RegisterActivity.class);
                intentRegister.putExtra("registerType", 1);
                startActivity(intentRegister);
                break;
            case R.id.tv_clause:
                Intent intentWeb = new Intent(baseContext, WebActivity.class);
                intentWeb.putExtra("tag", 3);
                startActivity(intentWeb);
                break;
            case R.id.iv_wx_login:
                WXEntryActivity.loginWeiXin();
                break;
            default:
                break;
        }
    }

    /**
     * 验证码请求
     */
    public Request<String> mRequest;

    private void SendYzm() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "sendValidateMCD");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("phone", phone);
            mRequest.add("flag", "0");
            // 添加到请求队列
            CallServer.getRequestInstance().add(VerificaActivity.this, mRequest,
                    new CustomHttpListener<VerifyCodeM>(VerificaActivity.this, true, VerifyCodeM.class) {
                        @Override
                        public void doWork(VerifyCodeM data, String code) {
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {

                            try {//{"msgcode":"1","msg":"成功","data":{"code":"06641"}}
                                super.onFinally(obj, code, isSucceed);
                                if ("1".equals(code)) {
                                    setVerifica(Verifica);
                                } else {
                                    CommonUtil.showToask(VerificaActivity.this, obj.getString("msg"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {

        }
    }


    /**
     * 用户登录
     *
     * @param loginType 0 验证码登录
     *                  1 密码登录
     */
    private void loginByType(int loginType) {
        try {
            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "Login");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("type", loginType);
            mRequest.add("phone", phone);
            if (isLoginType == 1) {
                mRequest.add("pwd", yzm);
            } else if (isLoginType == 2) {
                mRequest.add("pwd", pwd);
            }
            // 添加到请求队列
            CallServer.getRequestInstance().add(VerificaActivity.this, mRequest,
                    new CustomHttpListener<UserByApp>(VerificaActivity.this, true, UserByApp.class) {
                        @Override
                        public void doWork(UserByApp data, String code) {

                            LogUtils.i(data.toString());

                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                LogUtils.e(obj.toString());
                                if ("1".equals(code)) {
                                    ToastUtils.showShort("登录成功~");
                                    JSONObject object = obj.getJSONObject("data");
                                    AppConfig.getInstance().putBoolean("isLogin", true);
                                    AppConfig.getInstance().putString("uid", object.getString("uid"));
                                    AppConfig.getInstance().putString("userName", object.getString("userName"));
                                    AppConfig.getInstance().putString("nickName", object.getString("nickName"));
                                    AppConfig.getInstance().putString("realName", object.getString("realName"));
                                    AppConfig.getInstance().putString("password", object.getString("password"));
                                    AppConfig.getInstance().putString("salt", object.getString("salt"));
                                    AppConfig.getInstance().putString("photo", object.getString("photo"));
                                    AppConfig.getInstance().putString("paypassword", object.getString("paypassword"));
                                    AppConfig.getInstance().putString("status", object.getString("status"));
                                    AppConfig.getInstance().putString("sharevalue", object.getString("sharevalue"));
                                    AppConfig.getInstance().putString("sharevalue_u", object.getString("sharevalue_u"));
                                    AppConfig.getInstance().putString("parktime", object.getString("parktime"));
                                    AppConfig.getInstance().putString("incomevalue", object.getString("incomevalue"));
                                    AppConfig.getInstance().putString("isRealNameAuth", object.getString("isRealNameAuth"));
                                    AppConfig.getInstance().putString("incomevalue", object.getString("incomevalue"));
                                    AppConfig.getInstance().putString("idcard", object.getString("idcard"));
                                    AppConfig.getInstance().putString("sex", object.getString("sex"));
                                    AppConfig.getInstance().putBoolean("isLogin", true);

                                    // 设置极光推送别名
                                    JPushInterface.setAlias(VerificaActivity.this, 2019, phone);

                                    finish();
                                } else {
                                    ToastUtils.showShort(obj.getString("msg"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCLose(CloseLoginEvent event) {
        LogUtils.i("do next thing ....");
        switch (event.getLoginType()) {
            case 1:
                Intent intent = new Intent(this, RegisterActivity.class);
                intent.putExtra("registerType", 2);
                startActivity(intent);
                break;
            case 2:
                ToastUtils.showShort("微信登录失败，请尝试重新登录~");
                break;
            case 3:
                ToastUtils.showShort("登录成功~~");
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
